//
//  JXProdListController.m
//  JiaoX
//
//  Created by 尹桥印 on 14/11/18.
//  Copyright (c) 2014年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXProdListController.h"
#import "SubCategory.h"
#import "CategoryDataTool.h"
#import "ProdCateHViewCell.h"
#import "ProdPromotion.h"
#import "HomeProdViewFrame.h"
#import "HomeProdItemCell.h"
#import "JXProdDetailCtl.h"
#import "JXProdDetailCtl.h"

@interface JXProdListController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    JXProdListRequestType _requestType;
}
@property(nonatomic,weak)UICollectionView *collectView;
@property(nonatomic,weak)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *prodArray;
@property(nonatomic,strong)NSMutableArray *productFrames;

@property(nonatomic,copy)NSString *requestId;
@property(nonatomic,copy)NSString *pageTitle;
@property(nonatomic,strong)ProductSearch *result;//从搜索页面传入的


@end

@implementation JXProdListController

- (instancetype)initWithSubCategory:(SubCategory *)sub
{
    self = [super init];
    if (self) {
        _requestType = JXProdListRequestTypeCategory;
        _pageTitle = sub.categoryName;
        _requestId = sub.categoryId;
    }
    return self;
}

-(instancetype)initWithSearchResult:(ProductSearch *)result pageTitle:(NSString *)title{
    self = [super init];
    if (self) {
        _requestType = JXProdListRequestTypeCategory;
        _pageTitle = title;
        _result = result;
    }
    return self;
}

-(instancetype)initWithRequestId:(NSString *)requestId type:(JXProdListRequestType)type{
    self = [super init];
    if (self) {
        _requestType = type;
        _requestId = requestId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_switch" highImageName:@"navigationbar_switch_highlighted" target:self action:@selector(switchProdList)];
    
    self.title = self.pageTitle;
    _prodArray = [NSMutableArray array];
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    UICollectionView *collectView  =[[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    collectView.backgroundColor = JXGlobalColorBg;
    [collectView registerClass:[ProdCateHViewCell class] forCellWithReuseIdentifier:PROD_IDENTIFIER];
    collectView.delegate = self;
    collectView.dataSource=self;
    _collectView = collectView;
    [self.view addSubview:collectView];

    
    _productFrames = [NSMutableArray array];
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,NavHeight, self.view.width, self.view.height-NavHeight) style:UITableViewStylePlain];
    JXLog(@"self.view.width=%f",self.view.width);
    [self.view addSubview:tableView];
    tableView.hidden = YES;
    tableView.delegate = self;
    tableView.dataSource = self;
    //去掉tableview的分割线
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _tableView = tableView;
    
    if(![Utils isBlankString:self.requestId]){
        [self requestData];
    }else{
        [self loadDatas:self.result];
    }
}

-(void)switchProdList{
    BOOL hidden = _tableView.hidden;
    _tableView.hidden = !hidden;
    _collectView.hidden =hidden;
}

-(void)requestData{
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    //type 类型，如果为1则是请求品牌下面的列表，如果为2则是请求分类下面的列表
    [params setObject:self.requestId forKey:@"categoryId"];
    [params setObject:[NSString stringWithFormat:@"%ld",_requestType] forKey:@"type"];
    
    [CategoryDataTool prodListWithParam:params success:^(ProductSearch *result) {
        if(result.code==0){
            if (_requestType != JXProdListRequestTypePools) {
                result.productList = result.productList.reverseObjectEnumerator.allObjects;
            }
            [self loadDatas:result];
        }else{
            //弹出通知。
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        //弹出通知
        [DialogUtils showTipsWithView:self.navigationController.view String:@"加载失败"];
    }];
}

-(void)loadDatas:(ProductSearch *)result{
    [_prodArray removeAllObjects];
    [_prodArray addObjectsFromArray:result.productList];
    [_collectView reloadData];
    if(![Utils isBlankString:result.categoryName]){
        [self setTitle:result.categoryName];
    }
    [_productFrames removeAllObjects];
    for (ProductItemInfo *prod in result.productList) {
        HomeProdViewFrame *frame = [[HomeProdViewFrame alloc]init];
        frame.product = prod;
        [_productFrames addObject:frame];
    }
    [_tableView reloadData];

}



#pragma Mark - UICollectionView DataSource & delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _prodArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ProdCateHViewCell *cell = [ProdCateHViewCell cellWithTableView:collectionView indexPath:indexPath];
    
    BOOL isAdd = false;
    //获取到当前是第几个
    long index = indexPath.row;
    //判断是左边这列还是右边这列
    if(index%2){
        //右边这列,需要判断下一个是否有赠品
        ProductItemInfo *preItemInfo = _prodArray[index-1];
        if(preItemInfo.prodPromotion.presentList.count>0){
            //有赠品
            isAdd = true;
        }
    }else{
        //判断上一个是否有赠品
        if(index+1<_prodArray.count){
            //代表有下一个
            ProductItemInfo *nextItemInfo = _prodArray[index+1];
            if(nextItemInfo.prodPromotion.presentList.count>0){
                //有赠品
                isAdd = true;
            }
        }
    }
    [cell setProdData:_prodArray[indexPath.row] isAdd:isAdd];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat width = (JXScreenW-3*JXPublicInset)*0.5;
    
    //获取到当前是第几个
    long index = indexPath.row;
    //取出第几个对应的商品条目
    ProductItemInfo *itemInfo = _prodArray[index];
    
    //首先判断自己是否有赠品
    if(itemInfo.prodPromotion.presentList.count>0){
        //有赠品
        return CGSizeMake(width, PRODCATEHVIEW_LARGE_HEIGHT);
    }else{
        //判断是左边这列还是右边这列
        if(index%2){
            //右边这列,需要判断下一个是否有赠品
            ProductItemInfo *preItemInfo = _prodArray[index-1];
                if(preItemInfo.prodPromotion.presentList.count>0){
                    //有赠品
                    return CGSizeMake(width, PRODCATEHVIEW_LARGE_HEIGHT);
            }
        }else{
            //判断上一个是否有赠品
            if(index+1<_prodArray.count){
                //代表有下一个
                ProductItemInfo *nextItemInfo = _prodArray[index+1];
                if(nextItemInfo.prodPromotion.presentList.count>0){
                    //有赠品
                    return CGSizeMake(width, PRODCATEHVIEW_LARGE_HEIGHT);
                }
            }
        }
    }
    return CGSizeMake(width, PRODCATEHVIEW_SMALL_HEIGHT);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ProductItemInfo *itemInfo = _prodArray[indexPath.row];
    JXProdDetailCtl *proddc = [[JXProdDetailCtl alloc]initWithPordId:[NSString stringWithFormat:@"%d",itemInfo.prodId]];
    [self.navigationController pushViewController:proddc animated:YES];
}

#pragma Mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _productFrames.count;
}

/**
 *  返回对应位置的cell
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeProdItemCell *cell = [HomeProdItemCell cellWithTableView:tableView];
    cell.homeProdFrame = _productFrames[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    return cell;
}


#pragma mark - Table view 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeProdViewFrame *frame = _productFrames[indexPath.row];
    return frame.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ProductItemInfo *itemInfo = _prodArray[indexPath.row];
    JXProdDetailCtl *ctl = [[JXProdDetailCtl alloc]initWithPordId:[NSString stringWithFormat:@"%d",itemInfo.prodId]];
    [self.navigationController pushViewController:ctl animated:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}




@end
